<?php
require_once ('config.php');
require_once ('databasefunctions.php');
require_once ('displayfunctions.php');
require_once ('businessfunctions.php');
validate_user();
html_header();

//Show menu

switch ($_GET['action']) {

        case "add_form" :
                if ($_GET['sub_action'] == 'modify') {
                        title_bar($langtransactionlist, 1);
                        echo "<br>" . $langoperation . " - " . $langmodify . "<br>";

                        $sql = "SELECT * FROM billtransaction WHERE TransactionID = " . $_GET['TransactionID'];
                        $sql_result = sql_execute($sql);
                        $sql_data = mysql_fetch_array($sql_result);
                }
                else {
                        title_bar($langtransactionlist);
                        echo "<br>" . $langoperation . " - " . $langadd . "<br>";
                }
                ?>
                <form method = "GET" action="billtransaction.php" name = "transaction">
                <table>
                        <tr>
                                <td bgcolor='<? echo $color1 ?>'><? echo $langcompanyid ?>
                                <td><select name='CompanyID'>
                                        <?
                                                $company_list = get_company_list();
                                                foreach ($company_list as $company) {
                                                        echo "<option value='" . $company['CompanyID'] . "'";
                                                        if ($sql_data['CompanyID'] == $company['CompanyID']) echo " SELECTED ";
                                                        echo ">";
                                                        echo $company['CompanyID'] . " - " . $company['CompanyName'];
                                                }
                                        ?>
                                        </select>
                        <tr>

                                <td bgcolor='<? echo $color1 ?>'><? echo $langclientid ?>
                                <td><input type = "text" name ="ClientID" size = "10" maxlength="10" <?
                                        if ($sql_data['ClientID']) echo "value ='" . $sql_data['ClientID'] . "'";
                                        else if ($_SESSION['saved']['ClientID']) echo "value ='" . $_SESSION['saved']['ClientID'] . "'";
                                        ?> onBlur="ToUpperCase(document.transaction.ClientID);">
                                        <input type = 'button' value = 'S' onclick=opensearch('client','transaction.ClientID')>
                                        &nbsp;&nbsp;
                                        Prj / Wbs
                                        &nbsp;
                                        <input type = "text" name ="ClientPrj" size = "22" maxlength="50" <?
                                        if ($sql_data['ClientPrj']) echo "value ='" . $sql_data['ClientPrj'] . "'";
                                        else if ($_SESSION['saved']['ClientPrj']) echo "value ='" . $_SESSION['saved']['ClientPrj'] . "'";
                                        ?> onBlur="ToUpperCase(document.transaction.ClientPrj)">
                                        <input type = 'button' value = 'S' onclick=opensearch('project','transaction.ClientPrj')>
                        <tr>
                                <td bgcolor='<? echo $color1 ?>'><? echo $langjobid ?>
                                <td><input type = "text" name ="JobID" size = "10" maxlength="10" <?
                                        if ($sql_data['JobID']) echo "value ='" . $sql_data['JobID'] . "'";
                                        else if ($_SESSION['saved']['JobID']) echo "value ='" . $_SESSION['saved']['JobID'] . "'";
                                        ?> onBlur="ToUpperCase(document.transaction.JobID)">
                                        <input type = 'button' value = 'S' onclick=opensearch('job','transaction.JobID')>
                        <tr>
                                <td bgcolor='<? echo $color1 ?>'><? echo $langchargeid ?>
                                <td><select name='ChargeID'>
                                        <?
                                                $charge_list = get_charge_list('exp');
                                                foreach ($charge_list as $charge) {
                                                        echo "\n<option value='" . $charge['ChargeID'] . "'";
                                                        if ($sql_data['ChargeID'] == $charge['ChargeID']) echo " SELECTED ";
                                                        else if ($_SESSION['saved']['ChargeID'] == $charge['ChargeID']) echo " SELECTED ";
                                                        echo ">";
                                                        // echo $charge['ChargeID'] . " - " . $charge['ChargeDescription'];
                                                        echo $charge['ChargeDescription'];
                                                }
                                        ?>
                                        </select>
                        <tr>
                                <td bgcolor='<? echo $color1 ?>'><? echo $langstaffid ?>
                                <td>
                                        <?
                                        // only controller can select different staff
                                        if ($_SESSION['AccessLevel'] <= 2) {
                                                echo "\n<select name='StaffID'>";
                                                $staff_list = get_staff_list();
                                                foreach ($staff_list as $member) {
                                                        echo "\n<option value='" . $member['StaffID'] . "'";
                                                        if ($sql_data['StaffID'] == $member['StaffID']) echo " SELECTED ";
                                                        echo ">";
                                                        echo $member['StaffID'] . " - " . $member['StaffName'];
                                                }
                                                echo "\n</select>";
                                        }
                                        else {
                                                echo "<input type = 'text' name = 'StaffID' value = '" . $_SESSION['UserID'] . "' readonly>";
                                        }
                                        ?>
                        <tr>
                                <td bgcolor='<? echo $color1 ?>'><? echo $langquantity ?>
                                <td><input type = 'text' name = 'Quantity' maxlength = '10'
                                        <?
                                        if ($sql_data['Quantity']) echo " value = " . $sql_data['Quantity'];
                                        else if ($_SESSION['saved']['Quantity']) echo "value=" . $_SESSION['saved']['Quantity'];
                                        else echo " value = 1";
                                        ?>
                                        >
                        <tr>
                                <td bgcolor='<? echo $color1 ?>'><? echo $langamount ?>
                                <td><input type = 'text' name = 'ChargeRate' maxlength = '10'
                                        <?
                                        if ($sql_data['ChargeRate']) echo " value = " . $sql_data['ChargeRate'];
                                        else if ($_SESSION['saved']['ChargeRate']) echo "value=" . $_SESSION['saved']['ChargeRate'];
                                        else echo " value = 0.00";
                                        ?>
                                        >
                                <input name="NetRate" type="checkbox" value="ON"
                                        <?
                                        if (($sql_data['NetRate']) && ($sql_data['NetRate']==1)) echo "checked";
                                        else if (($sql_data['NetRate']) && ($sql_data['NetRate']==0)) echo "";
                                        else if ($_SESSION['saved']['NetRate']) echo "checked";
                                        ?>
                                >
                                <? echo $langnetrate ?>
                                <input name="WithHeading" type="checkbox" value="ON"
                                        <?
                                        if (($sql_data['WithHeading']) && ($sql_data['WithHeading']==1)) echo "checked";
                                        else if (($sql_data['WithHeading']) && ($sql_data['WithHeading']==0)) echo "";
                                        else if ($_SESSION['saved']['WithHeading']) echo "checked";
                                        ?>
                                >
                                <? echo $langwithheading ?>

                        <tr>
                                <td bgcolor='<? echo $color1 ?>'><? echo $langtaxrate ?>
                                <td><input type = 'text' name = 'TaxRate' maxlength = '5'
                                        <?
                                        if ($sql_data['TaxRate']) echo " value = " . $sql_data['TaxRate'];
                                        else if ($_SESSION['saved']['TaxRate']) echo "value ='" . $_SESSION['saved']['TaxRate'] . "'";
                                        else echo " value = 0.00";
                                        ?>
                                        >
                        <tr>
                        <SCRIPT LANGUAGE="JavaScript" ID="js1">
                        var cal1 = new CalendarPopup();
                        </SCRIPT>
                                <td bgcolor='<? echo $color1 ?>'><? echo $langtransactiondate ?>

                                <td><input type = 'text' name = 'TransactionDate' maxlength = '10'
                                        <?
                                        if ($sql_data['TransactionDate'])
                                            $user_date = convert_mysql_date($sql_data['TransactionDate']);
                                        else if ($_SESSION['saved']['TransactionDate'])
                                            $user_date = $_SESSION['saved']['TransactionDate'];
                                        else
                                            $user_date = convert_mysql_date(date('Y-m-d'));
                                        echo " value = '$user_date'";
                                        ?>
                                >
                                <input name="doty" value="" size="1"
                                onClick="document.forms[0].doty.value=day_of_the_year(document.forms[0].TransactionDate.value);"
                                onBlur="document.forms[0].TransactionDate.value=date_from_day_of_the_year(document.forms[0].doty.value,'ddMMyyyy');">
                                <A HREF="#" TITLE="Data" NAME="anchor1" ID="anchor1"
                                			onClick="cal1.select(document.forms[0].TransactionDate,'anchor1','ddMMyyyy'); return false;">
                                <img class='none' src="calendar.gif" border="0"></A>
                        <tr>
                                <td bgcolor='<? echo $color1 ?>'><? echo $langremark ?>
                                <td><textarea name=Remark cols=40 rows=2><?
                                        if (! empty($sql_data['Remark'])) echo $sql_data['Remark'] ?></textarea>
                </table>
                <br><input type = 'hidden' name = 'action' value = 'add'>
                        <?
                        if ($_GET['sub_action'] == 'modify') {
                                echo "<input type = 'hidden' name = 'sub_action' value = 'modify'>";
                                echo "<input type = 'hidden' name = 'TransactionID' value = '" . $_GET['TransactionID'] . "'>";
                                echo "<input type = 'submit' value = '$langmodify'>";
                        }
                        else {
                                echo "<input type = 'hidden' name = 'sub_action' value = 'add'>";
                                echo "<input type = 'submit' value = '$langadd'>";
                        }
                        ?>

                </form>
                <script>
                        function opensearch(search_type, fieldname) {
                                url_text = 'search.php?master=' + search_type + '&inputname=' + fieldname;
                                window.open(url_text ,'','width=700,height=500');
                }
                </script>
                <?
                break;

        case "add" :
                // AGMOD 25.12.2005 - Save some stuff in the session for subsequent retrieve
                $_SESSION['saved'] = $_GET;

                // validate client ID
                $sql = "SELECT ClientID FROM clientmaster WHERE Enable = 1 AND ClientID = '" . $_GET['ClientID'] . "'";
                $sql_result = sql_execute($sql);

                if (mysql_num_rows($sql_result) == 0) $error_text .= "<br>- $langclientid : $langnotexist<br>";

                // validate job ID
                $sql = "SELECT JobID FROM jobmaster WHERE Enable = 1 AND JobID = '" . $_GET['JobID'] . "'";
                $sql_result = sql_execute($sql);

                if (mysql_num_rows($sql_result) == 0) $error_text .= "<br>- $langjobid : $langnotexist<br>";

                // validate quantity
                if (! validate_number($_GET['Quantity'])) $error_text .= "<br>- $langinvalidquantity<br>";

                // get bill date
                if (! empty($_GET['TransactionDate'])) {
                        // validate date
                        $sql_date = validate_date($_GET['TransactionDate'], 1);
                }
                else {
                        // no transaction date entered, use today as transaction day
                        $datestamp = getdate();
                        $month = sprintf('%02d', $temp['mon']);
                        $day = sprintf('%02d', $temp['mday']);
                        $sql_date = $datestamp['year'] . "-" .
                                                sprintf('%02d', $datestamp['mon']) . "-" .
                                                sprintf('%02d', $datestamp['mday']);
                }

                if (! $sql_date) {
                        $error_text .= "<br>- $langinvaliddate<br>";
                }
                else {
                        if (! open_period_check($sql_date)) {
                                $error_text .= "<br>- $langoutofopenperiod<br>";
                        }
                }


                // Added 03.12.2005 - No ChargeRate is gonna be read from db if
                // charge type is expense footlist (amount is entered by user here!)
                if (get_charge_type($_GET['ChargeID'])!='F') {
                       $charge_rate = get_charge_rate($_GET['ChargeID'], $_GET['CompanyID'], strtoupper($_GET['ClientID']),
                                                  strtoupper($_GET['JobID']), $sql_date, $tax_rate);
                       if (! $charge_rate) $error_text .= "<br>- $langnochargerate<br>";
                } else {
                       // Added 02.12.2005 - ChargeRate is taken from GET vars if != 0
                       $charge_rate = $_GET['ChargeRate'];
                       // Added 02.12.2005 - TaxRate is taken from GET vars
                       $tax_rate = $_GET['TaxRate'];
                }

                if ($error_text) {
                        message_box($error_text);
                        echo "<script>history.go(-1)</script>";
                        exit;
                }

/*                // Added 02.12.2005 - ChargeRate is taken from GET vars if != 0
                if ($_GET['ChargeRate']!='0.00' and $_GET['ChargeRate'])
                        $charge_rate = $_GET['ChargeRate'];
                // Added 02.12.2005 - TaxRate is taken from GET vars
                if ($db_tax_rate=="0.00" or !$db_tax_rate) $tax_rate = $_GET['TaxRate'];*/

                // AGMOD 25.12.2005 - ChargeRate is Net?
                $net_rate = 0;
                if ($_GET['NetRate']=="ON")
                    $net_rate = 1;

                // AGMOD 29.07.2006 - Does transaction have Company Heading?
                $withHeading = 0;
                if ($_GET['WithHeading']=="ON")
                    $withHeading = 1;

                // AG: build common response string
                $response_str = "<br><br><h1>OK</h1><b>$langtransaction ";

                if ($_GET['sub_action'] == 'add') {
                        // insert transaction into table - billtransaction
                        $sql = "INSERT INTO billtransaction (CompanyID, ClientID, ClientPrj, JobID, ChargeID, ChargeRate, NetRate, TaxRate,
                                        WithHeading, StaffID, Quantity, TransactionDate, Remark, UpdateUser, UpdateProgram) values (";
                        $sql .= "'" . $_GET['CompanyID'] . "' ,";
                        $sql .= "'" . strtoupper($_GET['ClientID']) . "' ,";
                        $sql .= "'" . strtoupper($_GET['ClientPrj']) . "' ,";
                        $sql .= "'" . strtoupper($_GET['JobID']) . "' ,";
                        $sql .= "'" . $_GET['ChargeID'] . "' ,";
                        $sql .= $charge_rate . ", ";
                        $sql .= $net_rate . ", ";
                        $sql .= $tax_rate . ", ";
                        $sql .= $withHeading . ", ";
                        $sql .= "'" . $_GET['StaffID'] . "' ,";
                        $sql .= "'" . $_GET['Quantity'] . "' ,";
                        $sql .= "'$sql_date', ";
                        $sql .= "'" . $_GET['Remark'] . "' ,";
                        $sql .= "'" . $_SESSION['UserID'] . "' ,";
                        $sql .= "'" . $_SERVER['PHP_SELF'] . "')";
                        $sql_result = sql_execute($sql);
                        //die($sql);

                        echo $response_str."$langadded</b><br>";
                        ?>
                        <!-- AG: redirect to add new transaction -->
                        <script>setTimeout('location.href="billtransaction.php?action=add_form"',1000);</script>
                        <?

                }
                else { // $_GET['sub_action'] should be 'modify'
                        // update table - billtransaction
                        $sql = "UPDATE billtransaction SET ";
                        $sql .= "CompanyID = '" . $_GET['CompanyID'] . "', ";
                        $sql .= "ClientID = '" . strtoupper($_GET['ClientID']) . "', ";
                        $sql .= "ClientPrj = '" . strtoupper($_GET['ClientPrj']) . "', ";
                        $sql .= "JobID = '" . $_GET['JobID'] . "', ";
                        $sql .= "ChargeID = '" . $_GET['ChargeID'] . "', ";
                        $sql .= "ChargeRate = $charge_rate, ";
                        $sql .= "NetRate = $net_rate, ";
                        $sql .= "TaxRate = $tax_rate, ";
                        $sql .= "WithHeading = $withHeading, ";
                        $sql .= "StaffID = '" . $_GET['StaffID'] . "', ";
                        $sql .= "Quantity = " . $_GET['Quantity'] . ", ";
                        $sql .= "TransactionDate = '$sql_date', ";
                        $sql .= "Remark = '" . $_GET['Remark'] . "', ";
                        $sql .= "UpdateUser = '" . $_SESSION['UserID'] . "', ";
                        $sql .= "UpdateProgram = '" . $_SERVER['PHP_SELF'] . "' WHERE ";
                        $sql .= "TransactionID = " . $_GET['TransactionID'];
                        $sql_result = sql_execute($sql);

                        echo $response_str."$langmodified</b><br>";
                        ?>
                        <!-- AG: redirect to transactions list -->
                        <script>setTimeout('history.go(-2)',1000);</script>
                        <?

                }
                // title_bar($langtransactionlist, 1);

                break;

        case "delete" :
                $sql = "DELETE FROM billtransaction WHERE ";
                $sql .= "TransactionID = " . $_GET['TransactionID'];
                sql_execute($sql);

                echo "<br>$langtransaction $langdeleted<br>";
                ?>
                <!-- AG: redirect to transactions list -->
                <script>setTimeout('history.go(-2)',1000);</script>
                <?
                title_bar($langtransactionlist, 1);

                break;

        case "count" :
                // validate Effective Date
                if (! empty($_GET['from_TransactionDate'])) {
                        // convert user input effective date to format YYYYMMDD
                        $date_transaction_from = validate_date($_GET['from_TransactionDate'], 1) ;
                        if (! $date_transaction_from) {
                                ?>
                                <script>
                                        alert('<? echo $langinvaliddate . " : " . $langfrom . " Date" ?>');
                                        history.go(-1);
                                </script>
                                <?
                                exit;
                        }
                }

                if (! empty($_GET['to_TransactionDate'])) {
                        // convert user input effective date to format YYYYMMDD
                        $date_transaction_to = validate_date($_GET['to_TransactionDate'], 1) ;
                        if (! $date_transaction_to) {
                                ?>
                                <script>
                                        alert('<? echo $langinvaliddate . " : " . $langto . " Date" ?>');
                                        history.go(-1);
                                </script>
                                <?
                                exit;
                        }
                }

                save_search_list();
                $url_text = retrieve_search_list();
                $sql = select_statement('billtransaction');

                if ($_SESSION['AccessLevel'] >= 3)
                        $sql .= " AND StaffID = '" . $_SESSION['UserID']. "'";

                $sql_result = sql_execute($sql);
                $sql_data = mysql_fetch_array($sql_result);
                $no_of_record = $sql_data[0];
                ?>
                <script>
                this.location = 'billtransaction.php?action=browse&total_record=<? echo $no_of_record ?>&record_offset=0<? echo $url_text ?>'
                </script>
                <?
                break;

        case "browse" :
                navigation_bar($langtransactionlist,1);
                column_headings(array($langcompanyid, $langclientid, $langjobid, $langchargeid, $langstaffid,
                        $langtransactiondate, $langtimefrom, $langtimeto, $langprice, $langqtyhour, $langamount, $langnetrate,
                        $langtaxrate, $langremark, $langbilldate, $langbillno, $langsystemlog));

                $sql = select_statement('billtransaction', 1);

                if ($_SESSION['AccessLevel'] >= 3)
                        $sql .= " AND StaffID = '" . $_SESSION['UserID']. "'";

                $sql.= " ORDER BY StaffID, TransactionDate LIMIT " . $_GET['record_offset'] . ", " . $_SESSION['RecordPerPage'];
                $sql_result = sql_execute($sql);

                // AG: calculate TOTALS

                while ($sql_data = mysql_fetch_array($sql_result)) {
                        $rowcolor = row_color_change();
                        echo "\n<tr bgcolor='$rowcolor'>";

                        echo "<td nowrap>";
                        if (! $sql_data['FromTime']) {
                                echo "<a href = 'billtransaction.php?action=add_form&sub_action=modify";
                                echo "&TransactionID=" . $sql_data['TransactionID'];
                                echo "'>".$sql_data['CompanyID']."</a>";
                        }
                        else {
                                echo $sql_data['CompanyID'];
                        }

                        echo "<td nowrap>";
                        echo $sql_data['ClientID'];

                        echo "<td nowrap>";
                        echo $sql_data['JobID'];

                        echo "<td nowrap>";
                        echo $sql_data['ChargeID'];

                        echo "<td nowrap>";
                        echo $sql_data['StaffID'];

                        echo "<td nowrap>";
                        $user_date = convert_mysql_date($sql_data['TransactionDate']);
                        $user_date = substr($user_date,0,2) . "/" . substr($user_date,2,2) . "/" . substr($user_date,4,4);
                        echo $user_date;

                        echo "<td nowrap>";
                        echo $sql_data['FromTime'];

                        echo "<td nowrap>";
                        echo $sql_data['ToTime'];

                        echo "<td nowrap align='right'>";
                        echo $sql_data['ChargeRate'];

                        echo "<td nowrap align='right'>";
                        echo $sql_data['Quantity'];
                        $tot_quantity += $sql_data['Quantity'];

                        echo "<td nowrap align='right'>";
                        $amount = $sql_data['ChargeRate'] * $sql_data['Quantity'];
                        $tot_amount += $amount;
                        echo number_format($amount,2,'.','');

                        echo "<td nowrap>";
                        if ($sql_data['NetRate']==1) echo $langyes;
                        else echo $langno;

                        echo "<td nowrap align='right'>";
                        echo $sql_data['TaxRate'];

                        echo "<td nowrap>";
                        if (! empty($sql_data['Remark'])) {
                                echo "<a href='#' title='" . $sql_data['Remark'] . "'>$langyes</a>";
                        }
                        else {
                                echo $langno;
                        }

                        echo "<td nowrap>";
                        if (! empty($sql_data['BillNo'])) {
                                $user_date = convert_mysql_date($sql_data['BillDate']);
                                $user_date = substr($user_date,0,2) . "/" . substr($user_date,2,2) . "/" . substr($user_date,4,4);
                                echo $user_date;
                        }

                        echo "<td nowrap>";
                        echo $sql_data['BillNo'];

                        echo "<td nowrap>";
                        echo "<a href='#' title='" . $langupdateuser . " : " . $sql_data['UpdateUser'] . "\n";
                        $timestamp_date = substr($sql_data['UpdateTime'],0,4) . "-" .
                                                substr($sql_data['UpdateTime'],4,2) . "-" .
                                                substr($sql_data['UpdateTime'],6,2);
                        $user_date = convert_mysql_date($timestamp_date);
                        $user_date = substr($user_date,0,2) . "/" . substr($user_date,2,2) . "/" . substr($user_date,4,4);
                        $user_time = substr($sql_data['UpdateTime'],8,2) . ":" .
                                                 substr($sql_data['UpdateTime'],10,2) . ":" .
                                                 substr($sql_data['UpdateTime'],12,2);
                        echo $langupdatetime . " : $user_date $user_time \n";
                        echo $langupdateprogram . " : " . $sql_data['UpdateProgram'];
                        echo "'>$langdetails</a>";

                        echo "<td nowrap>";
                        if (empty($sql_data['BillNo'])) {
                                echo "<a href = 'billtransaction.php?action=delete";
                                echo "&TransactionID=" . $sql_data['TransactionID'];
                                echo "'>$langdelete</a>";
                        }
                }
                $tot_quantity = number_format($tot_quantity,2,'.','');
                $tot_amount = number_format($tot_amount,2,'.','');
                echo "<tr bgcolor='red'><td colspan='9'><b>$langtotal</b></td>";
                echo "<td align='right'><b>$tot_quantity</b></td>";
                echo "<td align='right'><b>$tot_amount</b></td></tr>";
                echo "</table>";
                break;

        default :
                title_bar($langtransactionlist, 1);

                $field[] = array('title'=>$langcompanyid, 'field'=>'CompanyID', 'length'=>10);
                $field[] = array('title'=>$langclientid, 'field'=>'ClientID', 'length'=>10);
                $field[] = array('title'=>$langjobid, 'field'=>'JobID', 'length'=>10);
                $field[] = array('title'=>$langstaffid, 'field'=>'StaffID', 'length'=>10);
                $field[] = array('title'=>$langtransactiondate, 'field'=>'TransactionDate', 'length'=>10);
                $field[] = array('title'=>$langchargeid, 'field'=>'ChargeID', 'length'=>10);
                $field[] = array('title'=>$langbillno, 'field'=>'BillNo', 'length'=>10);
                $field[] = array('title'=>$langbilldate, 'field'=>'BillDate', 'length'=>10);

                search_form($field, $_SERVER['PHP_SELF']);
                break;
}

html_footer();
?>
